<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>AdminLTE 3 | Data Tables</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <button id="add" class="btn btn-primary btn-sm">添加用户</button>
                        <button id="import" class="btn btn-primary btn-sm">批量导入</button>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                        <table id="example2" class="table table-bordered table-hover">
                        </table>
                    </div>
                    <!-- /.card-body -->
                </div>
            </div>
            <!-- /.col -->
        </div>
        <!-- /.row -->
    </section>
    <!-- /.content -->
    <footer class="main-footer text-center" style="margin-left: 0%;">
        <div class="d-none d-sm-block">
            <b>版本:</b> 1.0
        </div>
        <!-- 按钮触发模态框 -->
        <strong>Copyright &copy; 2014-2018 <a href="http://adminlte.io">咸阳恒源汽贸有限公司</a>.</strong>保留所有权.
    </footer>

    <!-- Control Sidebar -->
    <aside class="control-sidebar control-sidebar-dark">
        <!-- Control sidebar content goes here -->
    </aside>
    <!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->


<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="max-width: 1000px;">
        <div class="modal-content">
            <div class="modal-header">

                <h4 class="modal-title" id="myModalLabel">角色管理</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <!-- form start -->
                <form role="form" action="" id="form_submit">
                    <div class="row">
                        <div class="col-lg-2 mt-2">
                            <div class="">
                                <div style=" line-height: 1.5em;margin-top: 6px;" class="text-center"><code>*</code>&nbsp;&nbsp;角色编号
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-9 mt-2">
                            <div class="form-group">
                                <input name="code" type="text" class="form-control" id="u_id" placeholder=""
                                       disabled>
                                <input name="typeId" type="text" class="form-control" id="u_fid" placeholder=""
                                       style="display: none">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-2 mt-2">
                            <div class="">
                                <div style=" line-height: 1.5em;margin-top: 6px;" class="text-center"><code>*</code>&nbsp;&nbsp;角色名称
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-9 mt-2">
                            <div class="form-group">
                                <input name="name" type="text" class="form-control" id="name" value="">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-2">
                            <div class="">
                                <div style="line-height: 1.5em;margin-top: 6px;" class="text-center"><code>*</code>&nbsp;&nbsp;角色权限
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-9" id="function">

                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button id="save" type="button" class="btn btn-primary">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="uploadModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="max-width: 1000px;height: 400px">
        <div class="modal-content">
            <div class="modal-header">

                <h4 class="modal-title" id="myModalLabel">批量导入</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <!-- form start -->
                <form role="form" action="">

                    <div class="row">
                        <div class="col-lg-2">
                            <div class="">
                                <div style="line-height: 1.5em;margin-top: 6px;" class="text-center"><code>*</code>&nbsp;&nbsp;上传文件
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-9">
                            <div class="form-group">
                                <input name="fileName" type="text" class="form-control" id="fileName" value="">
                            </div>
                            <div id="msg-content">

                            </div>
                            <div id="uploadContainer" style="width: 100%"></div>

                        </div>
                    </div>


                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button id="importBtn" type="button" class="btn btn-primary">开始导入</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
<!--点击删除按钮后弹出的页面-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="height: 200px">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">
                    提示
                </h4>
                <!--<button type="button" class="close" data-dismiss="modal" aria-hidden="true">-->
                <!--&times;-->
                <!--</button> -->
            </div>
            <div class="modal-body">
                你确定要删除该条信息吗？
                <input id="del_id" style="display: none"/>
            </div>
            <div class="modal-footer">
                <button id="delBtn" type="submit" class="btn btn-primary" value="submit">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

<!-- page script -->
<script>
    $(function () {
        functionList();

        $("#myModal").on("hidden.bs.modal", function () {
            $('#myModal').removeData("bs.modal");
        });


        var user_table = $('#example2').DataTable({
            "language": {
                "url": "./plugins/datatables/chinese.txt"
            },
            "serverSide": true,
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "ajax": {
                "url": './RoleList.action?type=1',
                "type": 'POST'
            },
            columns: [
                {
                    "data": null,
                    "title": "序号",
                    width: 80,
                    "sClass": "text-tables-center text-center",
                    "createdCell": function (nTd, sData, oData, iRow, iCol) {
                        var startnum = this.api().page() * (this.api().page.info().length);
                        $(nTd).html(iRow + 1 + startnum); //分页行号累加：$(nTd).html(iRow+1);
                    }
                },
                {data: 'name', 'title': '名称', 'sClass': "text-center", width: 120},
                {
                    data: 'roleType.name', 'title': '功能权限', 'sClass': "text-center",
                    render: function (data, type, row) {
                        var str = "";
                        $.each(row.userRoles, function (i, val) {
                            str += '<button type="button" class="btn  btn-outline-primary float-left m-1" style="width: 9%">'
                            str += val.subMenu.name;
                            str += '</button>'
                        });
                        return str;
                    }
                },
                {
                    data: 'name', 'title': '操作', 'sClass': "text-center",
                    render: function (data, type, row) {
                        var id = row.typeId == undefined ? -1 : row.typeId;//-1说明是新增，其余表示为编辑
                        return "<i class='fa fa-pencil l-fa edit-btn' style='cursor: pointer' id=\'" + id + "\'></i>&nbsp;&nbsp;<i class='fa fa-trash-o m-fa del-btn' style='cursor: pointer' id=\'" + id + "\'></i>";
                    }
                }
            ]
        });

        function userSearchBtn() {
            user_table.ajax.reload();   // 这边的user_table，是由初始化datatables的变量名
        }

        $("#importBtn").on("click", function SaveData() {
            $("#msg-content").empty();
            var name = $("#fileName").val();
            $("#importBtn").text("导入中...");
            if (name != null && name != "") {
                var url = "./batchImportData.action?type=1";
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: {
                        "name": name
                    },
                    dataType: "json",
                    success: function (result) {
                        if (result.status == 200) {
                            userSearchBtn();
                            $("#msg-content").empty();
                            var text = "<label>数据导入成功!共计导入:<label style='color: red;font-size:18px'> " + result.total + "</label></font>条数据,成功:<label style='color: red;font-size:18px'>" + result.totalSuccess + "</label>条</label>"
                            $("#msg-content").append(text);
                            $("#importBtn").attr("disabled", "disabled");
                            $("#importBtn").text("导入完成");
                        } else {
                            $("#msg-content").empty();
                            var text = "<label style='color: red;font-size:18px'>" + result.message + "</label>"
                            $("#msg-content").append(text);
                            $("#importBtn").attr("disabled", "disabled");
                            $("#importBtn").text("导入失败");
                        }


                    },
                    dataType: "json"
                });
            } else {
                $("#msg-content").empty();
                var text = "<label style='color: red;font-size:18px'>请先上传批量导入文件</label>"
                $("#msg-content").append(text);
                $("#importBtn").text("开始导入");
            }

        });

        //点击编辑图标出现编辑框
        $("#example2 tbody").unbind('click').on("click", ".edit-btn", function () {
            var id = $(this).attr("id");
            if (id != -1) {
                var url = encodeURI("./roleTypeDetail.action");
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: {
                        "contentId": id
                    },
                    dataType: "json",
                    success: function (result) {
                        if (result.success) {
                            //刷新表格
                            var data = result.data;
                            $("#u_id").val("FU00" + data.typeId);
                            $("#u_fid").val(data.typeId);
                            $("#name").val(data.name);

                            $("input:checkbox").prop("checked", false);
                            $.each(data.userRoles, function (i, val) {
                                    $("input:checkbox[value='" + val.subMenu.subMenuId + "']").prop("checked", true);
                                }
                            );


                            $("input:checkbox").each(function () {
                                var ischecked = $(this).prop("checked");
                                if (ischecked) {
                                    $(this).parent("span").css("background-color", "rgb(254, 110, 54)");

                                } else {
                                    $(this).parent("span").css("background-color", "#50a1f2");
                                }
                            });


                            $('#myModal').modal('show');
                        } else {

                        }
                    },
                    dataType: "json"
                });
            } else {
                $('#myModal').modal('show');
            }

        })
        ;

        //删除
        $("#example2 tbody").on("click", ".del-btn", function () {
            var id = $(this).attr("id");
            $("#del_id").val(id);

            $('#deleteModal').modal('show');
            $("#deleteModal").bind('hide.bs.modal', function () {
                $(".modal-backdrop").remove();
            });

            $("#deleteModal").on('hidden.bs.modal', '.modal', function () {
                $(this).removeData('bs.modal');
            });


        });


        //保存按钮
        $("#example2 tbody").on("click", ".save-btn", function () {
            var id = $(this).attr("id");
            var tds = $(this).parents("tr").children();
            var sTds = tds.length;
            var lisval = [];
            for (var i = 0; i < sTds; i++) {
                if (i < sTds - 1)
                    lisval.push(tds.eq(i).children("input").val());
                else lisval.push(tds.eq(i).children("input").val())
            }
            if (i == sTds - 1) lisval.push();
            if (lisval[1] == "") {
                toNotification("警告！", "证照属性设置不能为空！", "warning");
                return false;
            } else if (lisval[1].length > 10) {
                toNotification("警告！", "证照属性设置不能超过十个字符！", "warning");
                return false;
            } else {
                $.each(tds, function (i, val) {
                    var jqob = $(val);
                    //把input变为字符串
                    if (!jqob.has('i').length) {
                        var txt = jqob.children("input").val();
                        jqob.html(txt);
                    }
                });
                $(this).toggleClass("edit-btn fa-pencil");
                $(this).toggleClass("save-btn fa-save");
                //保存数据
                SaveData(lisval, id);
            }

        });

        $('#form_submit').bootstrapValidator({

            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'fa  fa-check',
                invalid: 'fa fa-times',
                validating: 'fa fa-refresh'
            },

            fields: {
                name: {
                    message: '用户名验证失败',
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        }
                    }
                },
                identityCard: {
                    validators: {
                        notEmpty: {
                            message: '身份证号码不能为空'
                        }
                    }
                },
                tel: {
                    validators: {
                        notEmpty: {
                            message: '手机号码不能为空'
                        }
                    }
                }
            }

        });


        //证照属性设置保存信息
        $("#save").on("click", function SaveData() {
            $.startLoading(true);
            $("#form_submit").bootstrapValidator('validate');//提交验证
            if ($("#form_submit").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
                var data = $('#form_submit').serialize();
                //序列化获得表单数据，结果为：user_id=12&user_name=John&user_age=20
                var submitData = decodeURIComponent(data, true);
                //submitData是解码后的表单数据，结果同上
                var url = encodeURI("./saveUserRoles.action");
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: data,
                    dataType: "json",
                    success: function (result) {
                        if (result.success) {
                            //刷新表格
                            $("#myModal").modal('hide');  //手动关闭
                            userSearchBtn();
                        } else {
                            //刷新表格
                            $("#myModal").modal('hide');  //手动关闭
                            userSearchBtn();
                        }

                        $("#myModal").bind('hide.bs.modal', function () {
                            $(".modal-backdrop").remove();
                        });

                        $.startLoading(false);
                    },
                    dataType: "json"
                });
            }
        });

        //证照属性设置新添加信息
        $("#add").on("click", function SaveData() {
            $("#u_id").val("");
            $("#u_fid").val("");
            $("#u_name").val("");
            $("#u_position").val("");
            $("#u_school").val("");
            $("#u_tel").val("");
            $("#identityCard").val("");
            $("#u_email").val("");
            $("#u_birth").val("");
            uploadImg();
            $('#myModal').modal('show');
        });

        //证照属性设置新添加信息
        $("#import").on("click", function SaveData() {
            importFile();
            $("#importBtn").text("开始导入");
            $("#fileName").val("");
            $("#msg-content").empty();
            $("#importBtn").removeAttr("disabled");
            $('#uploadModal').modal('show');
        });


        //证照属性设置删除
        $("#delBtn").on("click", function () {
            var id = $("#del_id").val();
            var data = {"contentId": id};
            var url = "./deleteUserAccount.action";
            //执行删除
            $.ajax({
                type: 'POST',
                url: url,
                data: data,
                dataType: "json",
                success: function (result) {
                    if (result.success) {

                        userSearchBtn();
                    } else {
                        userSearchBtn();
                    }
                    $('#deleteModal').modal('hide');
                },
                dataType: "json"
            });

        });

        //获得标识
        function getActionId() {
            return new Date().getTime();
        }

    })
    ;


    function functionList() {
        var url = encodeURI("./funcAuthorityList.action");
        $.ajax({
            type: 'POST',
            url: url,
            data: {},
            dataType: "json",
            success: function (result) {
                if (result.success) {
                    //刷新表格
                    var data = result.data;
                    var str = "";
                    $.each(data, function (i, val) {
                        str += '<div><div class=""><div style="line-height: 1.5em;margin-top: 6px;" class="text-left">';
                        str += val.text;
                        str += '</div></div>';
                        if (val.nodes != null) {
                            str += '<div class="mt-2">';
                            $.each(val.nodes, function (j, item) {
                                str += '<div class="col-lg-3"><div class="input-group"><div class="input-group-prepend"><span class="input-group-text" ><input name="ids" type="checkbox" value="' + item.Id + '"></span></div><label class="form-control" >'+ item.text +'</label></div></div>';
                            });
                            str += '</div>';
                        }

                        str += '</div><div class="clear"></div>';
                    });
                    $("#function").append(str);
                } else {

                }


                $(".col-lg-3").on("click", function () {
                    var span = $(this).find("span");
                    var check = $(this).find("input:checkbox");
                    var ischecked = check.prop("checked");
                    check.prop("checked", !ischecked);
                    if (!ischecked) {
                        span.css("background-color", "rgb(254, 110, 54)");
                    } else {
                        span.css("background-color", "#50a1f2");
                    }
                });


                $("input:checkbox").change(function () {
                    var ischecked = $(this).prop("checked");
                    if (ischecked) {
                        $(this).parent("span").css("background-color", "rgb(254, 110, 54)");

                    } else {
                        $(this).parent("span").css("background-color", "#50a1f2");
                    }
                });

            },
            dataType: "json"
        });
    }

</script>
</body>
</html>
